TOOL.Category = "Spawning"
TOOL.Name = "Spawn Point"
TOOL.Command = nil
TOOL.ConfigName = ""

AddCSLuaFile("userspawns.lua")

-- language shit here
if(CLIENT) then
	language.Add( "Tool_userspawns_name", "User Customizable Spawns" )
	language.Add( "Tool_userspawns_desc", "This tool allows you to set your own spawn point" )

	language.Add( "Tool_userspawns_0", "Primary fire: Creates a spawn point where you're aiming" )
	language.Add( "Tool_userspawns_1", "Secondary fire: Creates a spawn point where you're standing" )
	language.Add( "Tool_userspawns_reset", "Reset" )
end

function TOOL:LeftClick( trace )
	-- this should set your spawn to where you are aiming.
	-- meh use the trace
	if(SERVER) then
		local SpawnPos = trace.HitPos
		self:GetSWEP().Owner:SetNetworkedVector( "SpawnPos", SpawnPos )
	end
end

function TOOL:RightClick( trace )
	-- this should set your spawn to where you are standing
	if(SERVER) then
		local SpawnPos = self:GetSWEP().Owner:GetPos()
		self:GetSWEP().Owner:SetNetworkedVector( "SpawnPos" , SpawnPos)
	end
end

function TOOL:Think( trace )
	if CLIENT then
		local SpawnPos = self:GetSWEP().Owner:GetNetworkedVector("SpawnPos")
			if SpawnPos.x == 65536 then return end
		local spawn = {}
			spawn.x = SpawnPos.x
			spawn.y = SpawnPos.y
			spawn.z = SpawnPos.z
		spawn = Vector(spawn.x,spawn.y,spawn.z)
		local ang = Angle(0, 0 , 0)
	local effectdata = EffectData()
		effectdata:SetOrigin( spawn )
		effectdata:SetNormal( ang:Up())
		effectdata:SetMagnitude( .5 )
		effectdata:SetScale( .25 )
		effectdata:SetRadius( .5 )
	util.Effect( "ManhackSparks", effectdata )
	end
end

function TOOL.BuildCPanel( CPanel )
	-- Header
	CPanel:AddControl( "Header", { Text = "#Tool_userspawns_name", Description	= "#Tool_userspawns_desc" }  )
	
	-- Reset Button
	CPanel:AddControl( "Button", { Label = "#Tool_userspawns_reset", Text = "#Tool_userspawns_reset", Height = 200, Width = 200, Command = "userspawnreset" } )
end

function SpawnHook( pl )
	if(SERVER) then -- this is all server sided, though it should never be called.
		local SpawnPos = pl:GetNetworkedVector( "SpawnPos" )

		if SpawnPos.x != 65536 then -- make sure our spawn point exists :P
			pl:SetPos( SpawnPos ) -- move us there
		end
	end
end

function SpawnConnect( pl )
	pl:SetNetworkedVector( "SpawnPos", Vector(65536, 65536, 65536))
end

if(SERVER) then
	hook.Add( "PlayerSpawn", "TOOLCSpawner", SpawnHook )
	hook.Add( "PlayerInitialSpawn", "TOOLCSpawner2", SpawnConnect )
	concommand.Add("userspawnreset",SpawnConnect)
end